import json
# 将view需要的共同模块进行封装到一个文件
from utils.common_import import *
from utils.ext import inner_db, db_add_record, db_query_record, db_delete_record, db_update_record, db_transaction
from .model import Record, RecordsQuerySchema, RecordQuerySchema, EventUpdateSchema
import datetime, re

class Records(Resource):
    @request_arg_check(RecordsQuerySchema(), location="args")
    @exception_response()
    @jwt_required()
    def get(self):
        page_index = current_schema_instance["page_index"]
        per_page_items = current_schema_instance["per_page_items"]

        interval = current_schema_instance["query_interval"]
        start_time = (datetime.datetime.now() - datetime.timedelta(days=interval))
        account = current_schema_instance["account"]

        result = inner_db.session.query(Record).filter(Record.account == account, Record.create_time > start_time).paginate(page_index, per_page_items, False)

        items = []
        for item in result.items:
            record_dict = item.get_data_info()
            record_dict.pop('response')
            items.append(record_dict)
        data = dict(items=items, total_page=result.pages)

        return make_success_response(data)


class RecordSingle(Resource):
    @request_arg_check(RecordQuerySchema(), location="args")
    @exception_response()
    def get(self):
        record = inner_db.session.query(Record).filter(Record.id == current_schema_instance["id"]).one()

        logger.info(record)

        record_dict = record.to_dict()
        return make_success_response(record_dict)

class Event(Resource):
    @exception_response()
    def get(self):
        sql = "SELECT * FROM INFORMATION_SCHEMA.EVENTS WHERE EVENT_NAME = 'del_record_event';"

        resultProxy = inner_db.session.execute(sql)
        for r in  resultProxy.fetchall():
            d = dict(r.items())
            logger.info(d['EVENT_DEFINITION'])


        p = re.compile(r'[(](.*?)[)]', re.S)
        record_retain_day = re.findall(p, d['EVENT_DEFINITION'])
        event_status = d['STATUS']
        event_dict = {'record_retain_day': record_retain_day[0], 'record_status': event_status}

        return make_success_response(event_dict)

    # update
    @request_arg_check(EventUpdateSchema())
    @permission_auth("admin")                         ## 验证jwt获取的角色权限
    @exception_response()
    @db_transaction(inner_db.session)
    def put(self):

        logger.info(current_schema_instance)
        if "record_retain_day" in current_schema_instance:
            sql  = "ALTER EVENT del_record_event ON COMPLETION PRESERVE ENABLE  DO CALL del_record_procedure("+ str(current_schema_instance["record_retain_day"]) +") ; "
        else:
            sql  = "ALTER EVENT del_record_event ON COMPLETION PRESERVE "+ current_schema_instance["event_status"] +" ;"

        result = inner_db.session.execute(sql)


        return make_no_data_response(status=200, code=200, message="success")



